//
//  YWAssetsInventoryListTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/10/25.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWAssetsInventoryListTableViewController.h"
#import "YWAssetsInventoryDetailsTableViewController.h"
#import "YWAddNewAssetsInventoryTableViewController.h"

#import "YWAssetsInventoryListTableViewCell.h"

#import "UIColor+CustomColors.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "UIScrollView+EmptyDataSet.h"
#import "NSDate+YYAdd.h"
#import "MJRefresh.h"

#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWAssetCheckManager.h"
#import "YWQrcodeManager.h"
#import "YWAssetCheckManager.h"
#import "YWAssetCheckRecord.h"
#import "YWNoQrcodeSelectLocationTableViewController.h"
#import "YWDictMaintenanceType.h"
#import "YWEquipmentManager.h"
#import "YWNoQrcodeRights.h"
#import "YWLoginTool.h"

@interface YWAssetsInventoryListTableViewController ()<DZNEmptyDataSetDelegate, DZNEmptyDataSetSource,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray * dataSource;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) UIButton * scanButton;
@property (nonatomic, strong) UIButton * noScanButton;
@end

@implementation YWAssetsInventoryListTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"清点";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.page = 1;
    
    [self initNotificationRefresh];
    [self setupTableView];
    
    [self.view addSubview:self.noScanButton];
    [self.view addSubview:self.scanButton];
}


- (void)setupTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass: [YWAssetsInventoryListTableViewCell class] forCellReuseIdentifier:YWAssetsInventoryListTableViewCellIdentifier];
    _tableView.backgroundColor = [UIColor customBackgroudColor];
    _tableView.emptyDataSetDelegate = self;
    _tableView.emptyDataSetSource = self;
    _tableView.sectionFooterHeight = 0.0f;
    _tableView.tableFooterView = [[UIView alloc]init];
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, KbottomViewH, 0);
    _tableView.estimatedRowHeight = 44.0f;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    [self.view addSubview:_tableView];
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    _tableView.mj_footer.automaticallyHidden = YES;
    // 马上进入刷新状态
    [_tableView.mj_header beginRefreshing];
    
}

- (void)initNotificationRefresh{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView:) name:KRefreshAssetCheckRecordList object:nil];
}

- (void)refreshTop
{
    self.page = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)refreshFootor
{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType
{
    if (refreshType == YWTableViewFreshTypeUp) {
        self.page++;
    }
    NSInteger location = self.locationId?self.locationId:0;
    //请求数据刷新
    YWWeakSelf(weakSelf);
    [[YWAssetCheckManager shareManager] requestAssetCheckRecordWithPage:self.page pageSize:10 locationId:location WithComplete:^(BOOL success) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (refreshType == YWTableViewFreshTypeDown) {
                [weakSelf.tableView.mj_header endRefreshing];
            }else {
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            if (success) {
                weakSelf.dataSource = nil;
                [weakSelf.tableView reloadData];
            }
        });
    }];
}

- (void)refreshTableView:(id)sender{
    _dataSource = nil;
    [self.tableView reloadData];
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
        [_dataSource addObjectsFromArray:[[YWAssetCheckManager shareManager] assetCheckWithPage:self.page locationId:self.locationId ? self.locationId : 0]];
    }
    return _dataSource;
}

- (UIButton *)scanButton{
    if (!_scanButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        //[scanButton setImage:[UIImage imageNamed:@"temp_scanButton"] forState:UIControlStateNormal];
        //scanButton.layer.masksToBounds = YES;
        [button setTitle:@"扫码" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(handleScanButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(SCREEN_WIDTH/4, SCREEN_HEIGHT-64-KbottomViewH, SCREEN_WIDTH/4*3, KbottomViewH);
        _scanButton = button;
    }
    return _scanButton;
}
- (UIButton *)noScanButton{
    if (!_noScanButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"无码" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customYellowColor];
        [button addTarget:self action:@selector(handleNoScanBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(0, SCREEN_HEIGHT-64-KbottomViewH, SCREEN_WIDTH/4, KbottomViewH);
        _noScanButton = button;
    }
    return _noScanButton;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataSource[section] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YWAssetsInventoryListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWAssetsInventoryListTableViewCellIdentifier];
    [self configureAssetsInventoryListCell:cell atIndexPath:indexPath];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YWAssetsInventoryDetailsTableViewController * assetsInventoryDetails = [[YWAssetsInventoryDetailsTableViewController alloc] init];
    assetsInventoryDetails.checkRecord = self.dataSource[indexPath.section][indexPath.row];
    [self.navigationController pushViewController:assetsInventoryDetails animated:YES];
}

//计算cell高度
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return [tableView fd_heightForCellWithIdentifier:YWAssetsInventoryListTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWAssetsInventoryListTableViewCell *cell) {
//        [self configureAssetsInventoryListCell:cell atIndexPath:indexPath];
//    }];
//}

- (void)configureAssetsInventoryListCell:(YWAssetsInventoryListTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    YWAssetCheckRecord * checkRecord = self.dataSource[indexPath.section][indexPath.row];
    cell.checkRecord = checkRecord;
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

#pragma mark - table view section header view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWMaterialApplyTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor blackColor];
        label.tag = 2016;
        label.font = KTitleFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    NSArray *array = [self.dataSource[section] count]>0?self.dataSource[section]:nil;
    YWAssetCheckRecord * checkRecord = array.count?array[0]:nil;
    NSString *time = [YWCommonTool showChineseFormatterDate:checkRecord.createTime/1000];
    NSInteger weekDay = [NSDate dateWithTimeIntervalSince1970:checkRecord.createTime/1000].weekday;
    NSString *weekStr = [YWCommonTool weekDayString:weekDay-1];
    NSString * title = [NSString stringWithFormat:@"%@  %@",time,weekStr];
    return title;
}

- (void)handleNoScanBtnEvent:(id)sender{
    NSInteger value = [[[NSUserDefaults standardUserDefaults] objectForKey:KYWNoQrcodeTypeCheckRecordKey] integerValue];
    if (value==1) {
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"无码工作已被管理员禁止" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self doNoQrcode];
    }
}

- (void)doNoQrcode{
    YWNoQrcodeSelectLocationTableViewController *noQrcodeSlecetLocationVC = [[YWNoQrcodeSelectLocationTableViewController alloc] init];
    __weak __typeof(&*noQrcodeSlecetLocationVC) weakNoQrcodeSlecetLocationVC = noQrcodeSlecetLocationVC;
    noQrcodeSlecetLocationVC.isDoTempMission = NO;
    noQrcodeSlecetLocationVC.doMissionBlock = ^(NSInteger locationId) {
        BOOL isExistEqu = [[YWEquipmentManager shareManager] isExistEquipmentWithLocationId:locationId];
        if (isExistEqu) {
            __strong __typeof(&*weakNoQrcodeSlecetLocationVC) strongNoQrcodeSlecetLocationVC = weakNoQrcodeSlecetLocationVC;
            YWAddNewAssetsInventoryTableViewController *newAssetVC = [[YWAddNewAssetsInventoryTableViewController alloc] init];
            newAssetVC.locationId = locationId;
            [strongNoQrcodeSlecetLocationVC.navigationController pushViewController:newAssetVC animated:YES];
        }else{
            [YWCommonTool showTextHUDWithContent:@"此位置下无设备"];
        }
    };
    [self.navigationController pushViewController:noQrcodeSlecetLocationVC animated:YES];
}

//扫描
- (void)handleScanButtonEvent:(id)sender{
    [[YWQrcodeManager shareManager] clickScanButtonWithType:YWQrcodeScanTypeNomall ViewController:self completionBlock:^(NSString *qrcodeId, QRCodeReaderViewController *qrCodeReaderViewController) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [qrCodeReaderViewController dismissViewControllerAnimated:NO completion:^{
                YWAddNewAssetsInventoryTableViewController *newAssetVC = [[YWAddNewAssetsInventoryTableViewController alloc] init];
                newAssetVC.qrCodeId = qrcodeId;
                [self.navigationController pushViewController:newAssetVC animated:YES];
            }];
        });
    }];
}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
